<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['genealogy:activities:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['genealogy:activities:delete']"
            >删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
          <el-form-item label="活动名称" prop="activityName">
            <el-input
              v-model="queryParams.activityName"
              placeholder="请输入活动名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="活动类型" prop="typeId">
            <el-select
              v-model="queryParams.typeId"
              placeholder="请选择活动类型"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="item in activityTypeOptions"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="活动状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择活动状态"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="dict in activityStatusOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="活动时间" prop="activityTime">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <el-table
        v-loading="loading"
        :data="filteredActivityList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="活动ID" align="center" prop="id" />
        <el-table-column label="活动名称" align="center" prop="activityName" :show-overflow-tooltip="true" />
        <el-table-column label="活动类型" align="center" prop="typeName" />
        <el-table-column label="活动地点" align="center" prop="location" :show-overflow-tooltip="true" />
        <el-table-column label="活动时间" align="center">
          <template #default="scope">
            <div>{{ scope.row.activityStartTime }}</div>
            <div>至</div>
            <div>{{ scope.row.activityEndTime }}</div>
          </template>
        </el-table-column>
        <el-table-column label="参与人数" align="center">
          <template #default="scope">
            {{ scope.row.currentParticipants || 0 }}/{{ scope.row.maxParticipants }}
          </template>
        </el-table-column>
        <el-table-column label="活动状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="View"
              @click="handleDetail(scope.row)"
              v-hasPermi="['genealogy:activities:query']"
            >详情</el-button>
            <el-button
              type="primary"
              link
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['genealogy:activities:edit']"
            >修改</el-button>
            <el-button
              type="primary"
              link
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['genealogy:activities:delete']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 活动信息表单抽屉 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      :size="drawerSize"
      @close="handleCloseDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="formData.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        
        <el-form-item label="活动类型" prop="typeId">
          <el-select v-model="formData.typeId" placeholder="请选择活动类型" style="width: 100%">
            <el-option
              v-for="item in activityTypeOptions"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="formData.location" placeholder="请输入活动地点" />
        </el-form-item>
        
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
            v-model="formData.activityTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="参与人数上限" prop="maxParticipants">
          <el-input-number v-model="formData.maxParticipants" :min="1" :max="10000" />
        </el-form-item>
        
        <el-form-item label="活动状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择活动状态" style="width: 100%">
            <el-option
              v-for="dict in activityStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入活动描述" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 弹出详情内容 -->
    <el-dialog
      v-model="dialogVisible"
      class="custom-transition-dialog"
      title="活动类型"
      width="30%"
    > 
     <activeDetail :activeId="activeId"></activeDetail>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, toRefs, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import ActivityAPI from '@/api/activity.api';
import { useAppStore } from '@/store';
import { DeviceEnum } from '@/enums/index.js';
import activeDetail from '@/views/activity/activityDetail.vue';

// 活动详情内容
const activeId = ref('');
const dialogVisible = ref(false);
const router = useRouter();
const appStore = useAppStore();
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));

// 遮罩层
const loading = ref(false);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 活动列表
const activityList = ref([]);
// 日期范围
const dateRange = ref([]);
// 表单引用
const formRef = ref();

// 活动状态选项
const activityStatusOptions = ref([
  { value: '计划中', label: '计划中' },
  { value: '进行中', label: '进行中' },
  { value: '已完成', label: '已完成' },
  { value: '已取消', label: '已取消' }
]);

// 活动类型选项
const activityTypeOptions = ref([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  activityName: undefined,
  typeId: undefined,
  status: undefined
});

// 筛选后的活动列表
const filteredActivityList = computed(() => {
  let result = activityList.value;
  
  // 按活动类型筛选
  if (queryParams.typeId) {
    result = result.filter(item => item.typeId === queryParams.typeId);
  }
  
  // 按活动状态筛选
  if (queryParams.status) {
    result = result.filter(item => item.status === queryParams.status);
  }
  
  return result;
});

// 弹窗
const dialog = reactive({
  title: "新增活动",
  visible: false,
});

// 初始表单数据
const initialFormData = {
  id: undefined,
  activityName: '',
  typeId: undefined,
  location: '',
  activityTime: [],
  maxParticipants: 100,
  status: '计划中',
  description: ''
};

// 表单数据
const formData = ref({ ...initialFormData });

// 表单校验规则
const rules = reactive({
  activityName: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
  typeId: [{ required: true, message: "请选择活动类型", trigger: "change" }],
  location: [{ required: true, message: "请输入活动地点", trigger: "blur" }],
  activityTime: [{ required: true, message: "请选择活动时间", trigger: "change" }],
  maxParticipants: [{ required: true, message: "请输入参与人数上限", trigger: "blur" }],
  status: [{ required: true, message: "请选择活动状态", trigger: "change" }]
});

// 获取活动类型列表
const getActivityTypes = async () => {
  try {
    const res = await ActivityAPI.getActivityTypePage({
      pageNum: 1,
      pageSize: 100
    });
    activityTypeOptions.value = res.list;
  } catch (error) {
    console.error('获取活动类型失败', error);
  }
};

// 获取活动列表
const getList = async () => {
  loading.value = true;
  try {
    // 处理日期范围
    let params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      activityName: queryParams.activityName
    };
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0];
      params.endTime = dateRange.value[1];
    }
    
    const res = await ActivityAPI.getActivityPage(params);
    console.log(res)
    // 处理活动类型名称
    activityList.value = res.list.map(item => {
      const type = activityTypeOptions.value.find(type => type.id === item.typeId);
      return {
        ...item,
        typeName: type ? type.typeName : '未知类型'
      };
    });
    total.value = res.total;
  } catch (error) {
    console.error('获取活动列表失败', error);
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '计划中': return 'info';
    case '进行中': return 'success';
    case '已完成': return 'primary';
    case '已取消': return 'danger';
    default: return 'info';
  }
};

// 获取状态标签
const getStatusLabel = (status) => {
  const option = activityStatusOptions.value.find(item => item.value === status);
  return option ? option.label : status;
};

// 表单重置
const resetQuery = () => {
  dateRange.value = [];
  queryParams.pageNum = 1;
  queryParams.activityName = undefined;
  queryParams.typeId = undefined;
  queryParams.status = undefined;
  handleQuery();
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
  dialog.title = "新增活动";
  dialog.visible = true;
  formData.value = { ...initialFormData };
};

// 修改按钮操作
const handleUpdate = (row) => {
  dialog.title = "修改活动";
  dialog.visible = true;
  loading.value = true;
  
  ActivityAPI.getActivityForm(row.id).then(res => {
    const data = res;
    formData.value = {
      id: data.id,
      activityName: data.activityName,
      typeId: data.typeId,
      location: data.location,
      activityTime: [data.activityStartTime, data.activityEndTime],
      maxParticipants: data.maxParticipants,
      status: data.status,
      description: data.description
    };
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
};

// 详情按钮操作
const handleDetail = (row) => {
  activeId.value = row.id;
  dialogVisible.value = true;
  // router.push({ path: `/activity/detail/${row.id}` });
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      
      // 处理活动时间
      const submitData = {
        ...formData.value,
        activityStartTime: formData.value.activityTime[0],
        activityEndTime: formData.value.activityTime[1]
      };
      delete submitData.activityTime;
      
      try {
        let res;
        if (submitData.id) {
          res = await ActivityAPI.updateActivity(submitData.id, submitData);
        } else {
          res = await ActivityAPI.addActivity(submitData);
        }
        
        ElMessage.success(submitData.id ? '修改成功' : '新增成功');
        handleCloseDialog();
        getList();
      } catch (error) {
        console.error(submitData.id ? '修改活动失败' : '新增活动失败', error);
        ElMessage.error(submitData.id ? '修改失败' : '新增失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 关闭对话框
const handleCloseDialog = () => {
  dialog.visible = false;
  formRef.value?.resetFields();
  formData.value = { ...initialFormData };
};

// 删除按钮操作
const handleDelete = (row) => {
  const selectedIds = row?.id || ids.value.join(',');
  if (!selectedIds) {
    ElMessage.warning('请选择要删除的活动');
    return;
  }
  
  ElMessageBox.confirm('确认删除所选活动吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await ActivityAPI.deleteActivity(selectedIds);
      ElMessage.success('删除成功');
      getList();
    } catch (error) {
      console.error('删除活动失败', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }).catch(() => {});
};

onMounted(() => {
  getActivityTypes();
  getList();
});
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style> 